﻿using JzSport.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JzSport.WebApp.Promotional
{
    public partial class Create : System.Web.UI.Page
    {
        public static object s_lockDirObj = new object();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 获取活动类别列表

                BaseDataService bdService = new BaseDataService();
                BaseDataSummary summary = bdService.GetLatestSummary("ActivityCategory").Data;
                if (summary != null)
                {
                    List<BaseDataItem> categories = bdService.GetItemList(summary.Id).Data;
                    _ctlListActivityCategory.DataSource = categories;
                    _ctlListActivityCategory.DataBind();
                }
            }
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(_ctlEditAdministrators.Text))
            {
                Response.Write("<script>alert('创建失败!');</script>");
                return;
            }

            string[] administratorArray = _ctlEditAdministrators.Text.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
            int[] administrators = new int[administratorArray.Length];
            for(int index = 0; index < administratorArray.Length; index++)
            {
		        int administratorId = 0;
                if(int.TryParse(administratorArray[index], out administratorId))
                {
                    administrators[index] = administratorId;
                }
                else
                {
                    Response.Write("<script>alert('创建失败!');</script>");
                    return;
                }
            }

            string title = _ctlEditTitle.Text.Trim();
            string categoryCode = _ctlListActivityCategory.SelectedValue.Trim();
            string address = _ctlEditAddress.Text.Trim();
            string city = _ctlEditCity.Text.Trim();
            double longitude = 0;
            double latitude = 0;

            DateTime beginTime = DateTime.Now;
            if (!DateTime.TryParse(_ctlEditBeginTime.Text, out beginTime))
            {
                Response.Write("<script>alert('创建失败!');</script>");
                return;
            }
            DateTime endTime = DateTime.Now;
            if (!DateTime.TryParse(_ctlEditEndTime.Text, out endTime))
            {
                Response.Write("<script>alert('创建失败!');</script>");
                return;
            }
            if(beginTime>=endTime || endTime<=DateTime.Now)
            {
                Response.Write("<script>alert('创建失败!');</script>");
                return;
            }
            int maxPersonCount = 0;
            if(!int.TryParse(_ctlEditMaxPersonCount.Text, out maxPersonCount))
            {
                Response.Write("<script>alert('创建失败!');</script>");
            }
            if (maxPersonCount <= 0)
            {
                Response.Write("<script>alert('创建失败!');</script>");
            }

            int costPrePerson = 0;
            if (!int.TryParse(_ctlEditCostPrePerson.Text, out costPrePerson))
            {
                Response.Write("<script>alert('创建失败!');</script>");
            }
            if (costPrePerson <= 0)
            {
                Response.Write("<script>alert('创建失败!');</script>");
            }
            string description = _ctlEditDescription.InnerText;
            string previewImageUrl = string.Empty;
            string sponsor = _ctlEditSponsor.Text.Trim();

            if (string.IsNullOrEmpty(title)
                || string.IsNullOrEmpty(categoryCode)
                || string.IsNullOrEmpty(address)
                || string.IsNullOrEmpty(city)
                || string.IsNullOrEmpty(sponsor))
            {
                Response.Write("<script>alert('创建失败!');</script>");
                return;
            }

            #region 上传图片
            if (_ctlFile.HasFile)
            {
                string dir = HttpContext.Current.Server.MapPath("~/Resources/Promotional/Images");
                if (!System.IO.Directory.Exists(dir))
                {
                    lock (s_lockDirObj)
                    {
                        if (!System.IO.Directory.Exists(dir))
                        {
                            System.IO.Directory.CreateDirectory(dir);
                        }
                    }
                }
                string[] segments = _ctlFile.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                Guid imageId = Guid.NewGuid();
                string targetPath = string.Format("{0}/{1}.{2}", dir, imageId, segments.Last());
                _ctlFile.SaveAs(targetPath);
                previewImageUrl = string.Format("./Resources/Promotional/Images/{0}.{1}", imageId, segments.Last());
            }
            #endregion

            PromotionalActivityService service = new PromotionalActivityService();
            ServiceResult<bool> result = service.Create(title, categoryCode, address, city, longitude, latitude, beginTime, endTime, maxPersonCount,
                costPrePerson,
                description,
                previewImageUrl,
                sponsor,
                administrators);
            if (result.ErrorCode == ErrorCode.NoError && result.Data)
            {
                Response.Write(string.Format("<script>alert('创建成功!');window.location.href='{0}';</script>", Request.RawUrl));
            }
            else
            {
                Response.Write("<script>alert('创建失败!');</script>");
            }
        }
    }
}